/**
 * 主题 Composable
 *
 * 提供统一的主题管理逻辑，支持多平台（H5、小程序、App）
 *
 * 使用方法：
 * ```typescript
 * import { useTheme } from '@/composables/useTheme'
 *
 * const { themeStore, themeClass, themeStyle, isDark, primaryColor } = useTheme()
 * ```
 */

import type { ComputedRef } from 'vue'
import type { ThemeState } from '@/store'
import { computed, nextTick } from 'vue'
import { useThemeStore } from '@/store'

// 定义 useTheme 的返回类型
export interface UseThemeReturn {
  themeStore: ReturnType<typeof useThemeStore>
  themeClass: ComputedRef<{ 'theme-dark': boolean, 'theme-light': boolean }>
  themeStyle: ComputedRef<{ backgroundColor: string, color: string }>
  isDark: ComputedRef<boolean>
  primaryColor: ComputedRef<string>
  theme: ComputedRef<ThemeState['theme']>
  getThemeValue: (lightValue: string, darkValue: string) => string
  getPrimaryStyle: (property?: string) => Record<string, string>
  getCardStyle: () => Record<string, string>
  getButtonStyle: (type?: 'primary' | 'secondary') => Record<string, string>
  updateNavigationBar: () => void
  initPageTheme: () => (() => void) | undefined
  cleanupPageTheme: (unwatch?: (() => void)) => void
}

export function useTheme(): UseThemeReturn {
  const themeStore = useThemeStore()

  // 响应式的主题类名
  const themeClass = computed(() => ({
    'theme-dark': themeStore.isDarkMode,
    'theme-light': !themeStore.isDarkMode,
  }))

  // 响应式的主题样式（主要用于小程序端）
  const themeStyle = computed(() => ({
    backgroundColor: themeStore.isDarkMode ? '#1a1a1a' : '#ffffff',
    color: themeStore.isDarkMode ? '#ffffff' : '#333333',
  }))

  // 常用的响应式值
  const isDark = computed(() => themeStore.isDarkMode)
  const primaryColor = computed(() => themeStore.getPrimaryColor)
  const theme = computed(() => themeStore.currentTheme)

  // 获取主题相关的样式值
  const getThemeValue = (lightValue: string, darkValue: string) => {
    return themeStore.isDarkMode ? darkValue : lightValue
  }

  // 获取带主色调的样式
  const getPrimaryStyle = (property: string = 'backgroundColor') => {
    return {
      [property]: themeStore.getPrimaryColor,
    }
  }

  // 获取卡片样式
  const getCardStyle = () => ({
    backgroundColor: getThemeValue('#ffffff', '#2a2a2a'),
    color: getThemeValue('#333333', '#ffffff'),
    borderColor: getThemeValue('#e5e5e5', '#333333'),
  })

  // 获取按钮样式
  const getButtonStyle = (type: 'primary' | 'secondary' = 'primary') => {
    if (type === 'primary') {
      return {
        backgroundColor: themeStore.getPrimaryColor,
        color: '#ffffff',
        borderColor: themeStore.getPrimaryColor,
      }
    }
    else {
      return {
        backgroundColor: 'transparent',
        color: themeStore.getPrimaryColor,
        borderColor: themeStore.getPrimaryColor,
      }
    }
  }

  // 小程序端主题变化处理
  let themeChangeHandler: ((data: any) => void) | null = null

  // #ifdef MP
  const handleThemeChange = (themeData: any) => {
    nextTick(() => {
      // 在小程序端强制触发重新渲染
      console.log('主题已更新:', themeData)
    })
  }

  themeChangeHandler = handleThemeChange
  // #endif

  // 初始化主题监听
  const initThemeListener = () => {
    // #ifdef MP
    if (themeChangeHandler) {
      uni.$on('theme-changed', themeChangeHandler)
    }
    // #endif
  }

  // 清理主题监听
  const cleanupThemeListener = () => {
    // #ifdef MP
    if (themeChangeHandler) {
      uni.$off('theme-changed', themeChangeHandler)
    }
    // #endif
  }

  // 设置导航栏颜色
  const updateNavigationBar = () => {
    try {
      uni.setNavigationBarColor({
        frontColor: themeStore.isDarkMode ? '#ffffff' : '#000000',
        backgroundColor: themeStore.isDarkMode ? '#1a1a1a' : '#ffffff',
        animation: {
          duration: 300,
          timingFunc: 'easeInOut',
        },
      })
    }
    catch (error) {
      console.warn('设置导航栏颜色失败:', error)
    }
  }

  // 页面级别的主题初始化
  const initPageTheme = () => {
    themeStore.initTheme()
    updateNavigationBar()
    initThemeListener()

    // 监听主题变化
    const unwatch = themeStore.$subscribe(() => {
      updateNavigationBar()
    })

    return unwatch
  }

  // 组件级别的主题清理
  const cleanupPageTheme = (unwatch?: (() => void)) => {
    cleanupThemeListener()
    unwatch?.()
  }

  return {
    // Store 实例
    themeStore,

    // 响应式值
    themeClass,
    themeStyle,
    isDark,
    primaryColor,
    theme,

    // 工具函数
    getThemeValue,
    getPrimaryStyle,
    getCardStyle,
    getButtonStyle,
    updateNavigationBar,

    // 生命周期管理
    initPageTheme,
    cleanupPageTheme,
  }
}

// 导出类型定义
export type ThemeComposable = UseThemeReturn
